package com.rederxu.cmd;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class CMD {
	private static String file = "/";
	private static final int CODE_INIT = 100;
	private static final int CODE_CMD = 101;
	
	/**
	 * 检测设备是否已有root权限
	 * */
	public static boolean haveRoot() {
        int i = execRootCmdSilent("echo test");
        if (i != -1) {
                return true;
        }
        return false;
	}

	/**
	 * 执行命令不需要打印结果
	 * */
	public static int execRootCmdSilent(String paramString) {
        try {
                Process localProcess = Runtime.getRuntime().exec("su");
                Object localObject = localProcess.getOutputStream();
                DataOutputStream localDataOutputStream = new DataOutputStream(
                                (OutputStream) localObject);
                String str = String.valueOf(paramString);
                localObject = str + "\n";
                localDataOutputStream.writeBytes((String) localObject);
                localDataOutputStream.flush();
                localDataOutputStream.writeBytes("exit\n");
                localDataOutputStream.flush();
                localProcess.waitFor();
                int result = localProcess.exitValue();
                return result;
        } catch (Exception localException) {
                localException.printStackTrace();
                return -1;
        }
	}
	

	/**
	 * 执行命令，并在listener中持续打印结果
	 * */
    public static void execRootCmd(final String paramString,final onCMDListener listener) {
    	handler.sendEmptyMessage(CODE_INIT);
    	if(paramString.equalsIgnoreCase("ls")){
    		String result = ls();
    		sendMessage(result,listener);
    		return;
    	}
    	if(paramString.startsWith("cd")){
    		String result = cd(paramString.replace("cd ", ""));
    		if(result != null){
	    		sendMessage(result,listener);
    		}
    		return;
    	}
    	
    	new Thread(){
			@Override
			public void run() {
					try {
	                    Process localProcess = Runtime.getRuntime().exec("su ");
	                    OutputStream localOutputStream = localProcess.getOutputStream();
	                    DataOutputStream localDataOutputStream = new DataOutputStream(
	                                    localOutputStream);
	                    InputStream localInputStream = localProcess.getInputStream();
	                    BufferedReader br=new BufferedReader(new InputStreamReader(localInputStream));
	                    String str1 = String.valueOf(paramString);
	                    String str2 = str1 + "\n";
	                    localDataOutputStream.writeBytes(str2);
	                    localDataOutputStream.flush();
	                    String str3 = null;
		                while ((str3 = br.readLine()) != null) {
		                    sendMessage(str3, listener);
		                }
	                    localDataOutputStream.writeBytes("exit\n");
	                    localDataOutputStream.flush();
	                    try {
							localProcess.waitFor();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	            } catch (IOException e) {
	                    e.printStackTrace();
	                    sendMessage(e.toString() + "\n失败可能原因：没有root权限", listener);
	            }
				super.run();
			}
    	}.start();
    }
    
    private static String cd(String path){
    	if(path.equalsIgnoreCase("..")){
    		if(file.equalsIgnoreCase("/")){
    			return "/";
    		}
    		File f = new File(file);
    		file = f.getParent();
    		return file + "\n";
    	}
    	String temp = file + path;
    	Log.d("temp", temp);
    	File f = new File(temp);
    	File fp = new File(path);
		String result = "\n";
    	if(f.exists() && f.isDirectory()){
    		file = temp;
    		return file + "\n";
    	}else if(fp.exists() && fp.isDirectory()){
    		file = path;
    		return file + "\n";
    	}
    	return result;
    }
    
    private static String ls(){
    	String temp = file;
    	Log.d("temp", temp);
    	File f = new File(temp);
		String result = "";
		if(f == null || f.listFiles() == null || !f.isDirectory()){
			file = "/";
			return "该目录不存在，已转到'/'\n";
		}
		result = "------------------------\n";
		for(File f1 : f.listFiles()){
			result += f1.getName() + "\n";
		}
		result += "------------------------\n";
    	return result;
    }
    
    private static Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case CODE_INIT:
				break;
			case CODE_CMD:
				onCMDListener listener = (onCMDListener) msg.obj;
				Bundle bundle = msg.getData();
//				Log.e("resilt lsx", bundle.getString("result"));
				listener.onCMD(bundle.getString("result"));
				break;
			}
			super.handleMessage(msg);
		}
    };
    
    private static void sendMessage(String result,onCMDListener l){
    	Message msg = new Message();
    	msg.what = CODE_CMD;
    	msg.obj = l;
    	Bundle bundle = new Bundle();
    	bundle.putString("result", result);
    	msg.setData(bundle);
    	handler.sendMessage(msg);
    }
}
